<?php

class Menu {
	var $navigation; // stores the relational tree
	var $items; // stores details for each item
	var $item_count; // stores the increasing unique ID for each item
	var $active_parent; // which parent nav item is active?
	
	function __construct () {
		$this->item_count = 0;
	}
	
	function parent_link ($system_name, $name,$link='#') {
		$this->navigation[$system_name] = array();
		$this->items[$system_name] = array(
									'system_name' => $system_name,
									'name' => $name,
									'link'=>$link,
								);
	}
	function child_link ($parent, $weight, $name, $link) {
		$item_id = $this->take_id();
		$this->navigation[$parent][$weight] = $item_id;
		$this->items[$item_id] = array(
										'name' => $name,
										'link' => $link
									);
	}
	function parent_active ($system_name) {
		return $this->active_parent = $system_name;
	}
	function display () {
		$return = '';
		if ($this->navigation){
		foreach ($this->navigation as $parent_id => $children) {
			ksort($this->navigation[$parent_id]);
		}
		
		reset($this->navigation);
		foreach ($this->navigation as $parent_id => $children) {
		    $current_system = $this->_process_active();
			$active_class = ($this->items[$parent_id]['link'] == current_url() || $this->active_parent == $this->items[$parent_id]['system_name'] || $current_system == $this->items[$parent_id]['system_name']) ? ' active': '';
			$onclick = ($this->items[$parent_id]['link'] == '#')?'onclick="return false"':'';
			$return .= '<li  class="nav-item"><a class="' . $active_class .'" title="' . $this->items[$parent_id]['name'] . '" '.$onclick.'  href="' . $this->items[$parent_id]['link'] . '">' . $this->items[$parent_id]['name'] . '</a>';
			if (!empty($this->navigation[$parent_id])) {		
				$return .= '<ul class="subnav" style="display:none">';
				foreach ($this->navigation[$parent_id] as $child_weight => $child_id) {
					if (isset($this->items[$child_id]['link'])) {
						$return .= '<li ><a title="' . $this->items[$child_id]['name'] . '" href="' . $this->items[$child_id]['link'] . '"><span>' . $this->items[$child_id]['name'] . '</span></a></li>';
					}
				}
				$return .= '</ul>';
			}
			$return .= '</li>';
			}
		}
		return $return;
	}
	function take_id () {
		$this->item_count++;
		return $this->item_count;
	}
	
	private function _process_active() {
	    $url = get_url();
	    $current_url = current_url();
	    $current_url = str_replace($url, '', $current_url);

	    $array = explode('/', $current_url);
	    return $array[0];
	}
}